package org.jeecg.modules.ncmeapis.network.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.ncmeapis.network.service.IdentityService;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.model.DepartIdModel;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class IdentityServiceImpl implements IdentityService {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysUserDepartService sysUserDepartService;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Override
    public void userExist(String userId) {
        if (sysUserService.getById(userId) == null) {
            throw new RuntimeException(NetworkErrorMsg.USER_NOT_EXIST);
        }
    }

    @Override
    public String getUserId() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return sysUser.getId();
    }

    @Override
    public List<String> getGroupIdsByUserId(String userId) {
        try {
            List<String> collect = sysUserDepartService.queryDepartIdsOfUser(userId).stream().map(DepartIdModel::getKey).collect(Collectors.toList());
            //添加角色id
            List<SysUserRole> list = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId));
            List<String> collect1 = list.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            collect.addAll(collect1);
            //添加租户id
            collect.add(sysUserService.getById(userId).getRelTenantIds());
            return collect;
        } catch (Exception e){
            return new ArrayList<>();
        }
    }

}
